package com.hzjh.base.web.core

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.webkit.WebSettings
import android.webkit.WebView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.hzjh.base.web.util.WebCacheUtil
import com.hzjh.base.web.util.WebUtil
import java.io.File

class JHWebView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : WebView(context, attrs), LifecycleEventObserver {
    private val TAG="GuangWebView"

    private val mWebViewClient by lazy { BaseWebViewClient(settings) }
    private val mWebChromeClient by lazy { BaseWebChromeClient() }
    private var userAgentString:String //记录初始值
    private var ifCacheWeb:Boolean=false //从webView Cache中获取到的
    private var jsBridge: JsBridgeBase?=null //jsBridge桥接
    private var webJsI: OnWebChangeListener?=null //交互接口
    init {
        // 白色背景
        setBackgroundColor(Color.TRANSPARENT)

        WebUtil.defaultSettings(settings)

        userAgentString=settings.userAgentString

        setLayerType(LAYER_TYPE_HARDWARE, null) //启动webView硬件加速
        isVerticalScrollBarEnabled = false
        isHorizontalScrollBarEnabled = false
        overScrollMode = OVER_SCROLL_NEVER

        addWebViewClient(mWebViewClient)
        addChromeClient(mWebChromeClient)
    }

    //监听事件
    fun setOnWebChangeListener(listener: OnWebChangeListener?) {
        this.webJsI=listener
        mWebViewClient.mListener=listener
        mWebChromeClient.mListener=listener
    }

    // jsBridge setting
    fun addJsBridge(jsBridge: JsBridgeBase, name:String="H5MallBridge"){
        this.jsBridge=jsBridge
        addJavascriptInterface(jsBridge, name)
    }

    //WebView开启可调式
    fun setDebugEnabled(enabled: Boolean) {
        setWebContentsDebuggingEnabled(enabled)
    }
    //设置webview背景
    @SuppressLint("ResourceType")
    override fun setBackgroundColor(color: Int) {
        if(color<=0){
            return
        }
        super.setBackgroundResource(color)
    }

    fun addWebViewClient(client: BaseWebViewClient) {
        webViewClient = client
    }
    fun addChromeClient(client: BaseWebChromeClient) {
        webChromeClient = client
    }

    /**
     * 设置是否使用缓存
     * 默认使用缓存 只有自己的H5链接使用拦截缓存
     */
    fun setUseCache(userCache:Boolean=true){
        var ifUseInterceptCache=userCache
        var ifUseWebCacheMode=userCache
        settings.cacheMode=if(ifUseWebCacheMode) WebSettings.LOAD_DEFAULT else WebSettings.LOAD_NO_CACHE
        mWebViewClient.ifUseCache=ifUseInterceptCache
    }
    //更新userAgentString
    private fun updateUserAgent(userAgentString:String){
        settings.userAgentString =userAgentString
    }
    //设置是否预加载的webview
    fun setCacheWeb(ifCacheWeb:Boolean){
        this.ifCacheWeb=ifCacheWeb
    }

    //自定义加载链接方法
    fun guangLoadUrl(url: String,userCache:Boolean=true) {

        if (WebUtil.isEmpty(url)) {
            return
        }
        setUseCache(userCache)
        if(ifCacheWeb){
            //命中预加载中的webview 不需要重新加载地址
            webJsI?.showLoadingAnim(!mWebChromeClient.ifLoadSuccess)
            return
        }

        //上次加载页面闪现问题处理 开启硬件加速后会好很多
        visibility= View.GONE //加载默认隐藏加载成功后展示

        postDelayed(
                {
                    visibility = View.VISIBLE
                    webJsI?.showLoadingAnim(!mWebChromeClient.ifLoadSuccess)//加载完成就不需要显示loading
                },
                200
            )//0.2秒后处理

        loadUrl(url)
    }

    override fun loadUrl(url: String) {
        super.loadUrl(url)
        //记录埋点的URL 包括重定向的URL在内
        mWebViewClient.putSpmLoadUrl(url)
    }

    //获取预加载的H5标题
    fun getPreWebTitle():String?{
        return mWebChromeClient.preWebTitle
    }

    override fun canGoBack(): Boolean {
        val backForwardList = copyBackForwardList()
        val currentIndex = backForwardList.currentIndex - 1
        if (currentIndex >= 0) {
            val item = backForwardList.getItemAtIndex(currentIndex)
            if (item?.url == "about:blank") {
                return false
            }
        }
        return super.canGoBack()
    }

    /**
    * 生命周期 onResume()
    */
    @SuppressLint("SetJavaScriptEnabled")
    override fun onResume() {
        super.onResume()
        settings.javaScriptEnabled = true
    }

    /**
     * 生命周期 onPause()
     */
    override fun onPause() {
        super.onPause()
    }

    /**
     * 生命周期 onDestroy()
     * 父类没有 需要自己写
     */
    fun onDestroy() {
        settings.javaScriptEnabled = false
        release()
    }


    //自定义destroy方法 主动触发销毁
    fun destroy(release:Boolean){
        if(release){
            super.destroy()
        }
    }
    /**
     * 重写destroy 否则webView缓存池会莫名被回收销毁
     */
    override fun destroy() {

    }

    //释放
    fun release(){
        setOnWebChangeListener(null)
        //被回收时 重置初始化参数
        mWebChromeClient.preWebTitle=null
        ifCacheWeb=false
        loadUrl("about:blank")
        mWebViewClient.clearSpmLoadUrl()
        (parent as ViewGroup?)?.removeView(this)
        removeAllViews()
    }

    //重写清理缓存方法
    override fun clearCache(includeDiskFiles: Boolean) {
        super.clearCache(includeDiskFiles)
        WebCacheUtil.clearPreWebView() //清理预加载页面
        if(includeDiskFiles){
            //清除磁盘缓存
            WebCacheUtil.clearCacheFolder(File(WebCacheUtil.getWebViewCachePath(context)))
        }
    }


    /**
     * 设置 WebView 生命管控（自动回调生命周期方法）
     */
    fun setLifecycleOwner(owner: LifecycleOwner) {
        owner.lifecycle.addObserver(this)
    }

    /**
     * 生命周期回调
     */
    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when (event) {
            Lifecycle.Event.ON_RESUME -> {
                onResume()
            }
            Lifecycle.Event.ON_STOP -> {
                onPause()
            }
            Lifecycle.Event.ON_DESTROY -> {
                source.lifecycle.removeObserver(this)
                onDestroy()
            }
            else -> {}
        }
    }

    interface OnWebChangeListener {
        fun titleChange(title: String?) //标题改变
        fun progressChange(progress: Int) //加载进度改变
        fun onInnerLinkChecked(url: String?) //跳转新的链接触发
        fun onWebLoadError() //加载失败
        fun onWebLoadStart(url: String) //加载开始
        fun onWebLoadFinish(url: String?) //加载完成
        //H5加载状态监听 埋点使用 url code location
        fun onWebLoadStatus(params:Map<String,String>) //加载链接状态
        fun showLoadingAnim(show:Boolean?) //展示loading
    }
}